package com.geor.gcv.core.mat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.opencv.core.Mat;

import com.geor.gcv.core.model.Area;
import com.geor.gcv.core.util.DataTool;

/**
 * 投影切分，简单的图片分割
 * 
 * @author geor.lusongnan
 *
 */
public class CellChipperSimpleImpl implements CellChipper {
	float l = 0.05f;
	float r = 0.95f;

	public CellChipperSimpleImpl(float l, float r) {
		super();
		this.l = l;
		this.r = r;
	}

	public CellChipperSimpleImpl() {
	}

	@Override
	public List<Area> execute(Mat mat) throws Exception {
		// mat必须二值化之后
		List<Integer> rows = Mats.getRows(mat, l, r);

		if (rows.size() >= 2) {
			int index = DataTool.getListPoorMaxValue(rows);
			List<Integer> cols = Mats.getCols(mat, Arrays.asList(rows.get(index), rows.get(index + 1)));
			return Mats.toAreas(Arrays.asList(rows.get(index), rows.get(index + 1)), cols);
		}
		return new ArrayList<Area>();
	}

	/**
	 * 取集合 间距最大的位置
	 * 
	 * @param rows
	 * @return
	 */
	public int getListPoorMaxValue(List<Integer> rows) {
		int row = 0;
		if (rows.size() == 2) {
			return row;
		}
		if (rows.size() > 2) {
			// 切割 行距 从而判断 在那一行切割
			List<Integer> lists = new ArrayList<Integer>();
			for (int i = 1; i < rows.size(); i += 2) {
				lists.add(rows.get(i) - rows.get(i - 1));
			}
			for (int i = 1; i < lists.size(); i++) {
				int poor = lists.get(row);
				if (poor < lists.get(i)) {
					row = i;
				}
			}
		}
		return row;
	}

	@Override
	public void setParams(Properties properties) {

	}

}
